package service

import (
	"context"
	"errors"
	corev1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/util/intstr"
	"log"
)

type servicev1 struct {}

var Service servicev1

type ServiceCreate struct {
	Name string `json:"name"`
	Namespace string `json:"namespace"`
	Type string `json:"type"`
	ContainerPort int32 `json:"container_port"`
	Port int32 `json:"port"`
	NodePort int32 `json:"node_port"`
	Label map[string]string `json:"label"`
}

//类型转换方法 corev1.Service -> DataCell
func (s *servicev1) toCell(services []corev1.Service) []DataCell {
	cell := make([]DataCell, len(services))
	for i := range services {
		cell[i] = serviceCell(services[i])
	}
	return cell
}

//类型转换方法  DataCell -> corev1.Service
func (s *servicev1) fromCells(cells []DataCell) []corev1.Service {
	services := make([]corev1.Service, len(cells))
	for i := range cells {
		// cells[i].(deploymentCell) 类型转换
		services[i] = corev1.Service(cells[i].(serviceCell))

	}
	return services
}

//定义列表的返回内容 Item是deploy元素列表  Total为元素数量
type ServiceResp struct {
	Item  []corev1.Service `json:"item"`
	Total int                 `json:"total"`
}

//获取 service 列表 支持过滤 排序 分页
func (s *servicev1) GetServices(filtername, namespacen string, limit, page int) (serviceResp *ServiceResp, err error) {
	//获取deploymentList类型的deploy列表
	serviceList, err := K8s.ClientSet.CoreV1().Services(namespacen).List(context.TODO(), metav1.ListOptions{})
	if err != nil {
		log.Printf("[ service ]资源列表获取失败：%s", err)
		return nil, errors.New("获取[ service ]列表失败" + err.Error())
	}

	selectableData := &dataSelector{
		GenericDataList: s.toCell(serviceList.Items),
		DataSelectQuery: &DataSelectQuery{
			FilterQuery: &FilterQuery{Name: filtername},
			PaginateQuary: &PaginateQuary{
				Limit: limit,
				Page:  page,
			},
		},
	}

	//先过滤
	filtered := selectableData.Filter()
	total := len(filtered.GenericDataList)
	//先排序再分页
	data := filtered.Sort().Paginate()

	services := s.fromCells(data.GenericDataList)

	return &ServiceResp{
		Total: total,
		Item:  services,
	}, nil

}


//获取 service 详情
func (s *servicev1) GetServiceDetail(serviceName, namespace string) (service *corev1.Service, err error) {

	service, err = K8s.ClientSet.CoreV1().Services(namespace).Get(context.TODO(), serviceName, metav1.GetOptions{})
	if err != nil {
		log.Printf("获取[ service ]详情失败：%s", err)
		return nil, errors.New("获取[ service ]详情失败：%s" + err.Error())
	}
	return service, nil
}


//创建service
func (s *servicev1)CreateService(data *ServiceCreate) (err error) {
	service := &corev1.Service{
		TypeMeta:   metav1.TypeMeta{},
		ObjectMeta: metav1.ObjectMeta{
			Name: data.Name,
			Namespace: data.Namespace,
			Labels: data.Label,
		},
		Spec:       corev1.ServiceSpec{
			Type: corev1.ServiceType(data.Type),
			Ports: []corev1.ServicePort{
				{
					Name: "http",
					Port: data.Port,
					Protocol: "TCP",
					TargetPort: intstr.IntOrString{
						Type:   0,
						IntVal: data.ContainerPort,
					},
				},
			},
			Selector: data.Label,
		},
		Status:     corev1.ServiceStatus{},
	}
	//默认clusterIP，判断是否nodeport 添加配置
	if data.NodePort != 0 && data.Type == "NodePort" {
		service.Spec.Ports[0].NodePort = data.NodePort
	}
	//创建service
	_,err = K8s.ClientSet.CoreV1().Services(data.Namespace).Create(context.TODO(),service,metav1.CreateOptions{})
	if err != nil {
		log.Printf("创建service失败：%s", err)
		return errors.New("创建service失败：%s" + err.Error())
	}
	return nil
}



//删除service
func (s *servicev1) DeleteService(servicename, namespace string) (err error) {
	err = K8s.ClientSet.CoreV1().Services(namespace).Delete(context.TODO(), servicename, metav1.DeleteOptions{})
	if err != nil {
		log.Printf("删除service失败：%s", err)
		return errors.New("删除service失败:" + err.Error())
	}
	return nil
}

























